﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.IO;
using System.Xml.Serialization;

namespace Qpm.Automap.Core.UI
{
    public partial class ContractorInfoPage : Wizard.UI.InternalWizardPage
    {
        private List<ContractorPartyType> m_contractorInfo;
        private ContractorPartyType m_currentContractor = null;

        public ContractorInfoPage()
        {
            InitializeComponent();
            this.Banner.Title = "Step 3 of 6 - Contractor Information";
            this.Banner.Subtitle = "Enter Contractor name, facility location, ans and authorized representatives: " + parameters.projectName;
        }

        private void ContractorInfoPage_SetActive(object sender, CancelEventArgs e)
        {
            SetWizardButtons(Wizard.UI.WizardButtons.Back | Wizard.UI.WizardButtons.Next);
            m_contractorInfo = GetContractorInfo();
            foreach (ContractorPartyType contractor in m_contractorInfo)
            {
                int rowIndex = dgv_Contractors.Rows.Add(); 
                dgv_Contractors.Rows[rowIndex].Cells[0].Value = contractor.Name==null?"":contractor.Name.Value;
                dgv_Contractors.Rows[rowIndex].Cells[1].Value = contractor.SpecifiedProjectOrganization.BusinessTypeCode == null ? "" : contractor.SpecifiedProjectOrganization.BusinessTypeCode.Value;
                dgv_Contractors.Rows[rowIndex].Cells[2].Value = contractor.SpecifiedProjectOrganization.ID == null ? "" : contractor.SpecifiedProjectOrganization.ID.Value;
                dgv_Contractors.Rows[rowIndex].Cells[3].Value = contractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0].LineOne.Value + 
                    ", " + contractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0].CityName.Value;
                if (dgv_Contractors.Rows[rowIndex].Cells[3].Value.ToString().Trim() == "" ||
                    dgv_Contractors.Rows[rowIndex].Cells[3].Value.ToString().Trim() == ",")
                {
                    dgv_Contractors.Rows[rowIndex].Cells[3].Value = "Click to enter address";
                }
                }
        }

        private void ContractorInfoPage_WizardNext(object sender, Wizard.UI.WizardPageEventArgs e)
        {
            parameters.contractorInfo = m_contractorInfo;
        }

        private List<ContractorPartyType> GetContractorInfo()
        {
            bool configExists = false;
            string fieldValue = string.Empty;
            XmlDocument configDoc = new XmlDocument();
            if (File.Exists(parameters.configFile))
            {
                configExists = true;
                configDoc.Load(parameters.configFile);
            }
            if (configExists)
            {
                XmlNode contractorNode = configDoc.SelectSingleNode("//ContractorData");
                fieldValue = contractorNode == null ? string.Empty : contractorNode.InnerText;
            }
            if (fieldValue.Length > 0)
            {
                StringReader sr = new StringReader(fieldValue);
                XmlSerializer xs = new XmlSerializer(typeof(ContractorPartyType[]));
                object obj = xs.Deserialize(sr);
                if (obj != null)
                {
                    ContractorPartyType[] contractors = obj as ContractorPartyType[];
                    return contractors.ToList();
                }
                return new List<ContractorPartyType>();
            }
            return new List<ContractorPartyType>();
        }

        private void PopulateChildGrids()
        {
            dgv_Contacts.Rows.Clear();
            dgv_Locations.Rows.Clear();
            if (m_currentContractor == null)
            {
                dgv_Contacts.AllowUserToAddRows = false;
                dgv_Contacts.AllowUserToDeleteRows = false;
                dgv_Locations.AllowUserToDeleteRows = false;
                dgv_Locations.AllowUserToAddRows = false;
                return;
            }
            else
            {
                dgv_Contacts.AllowUserToAddRows = true;
                dgv_Contacts.AllowUserToDeleteRows = true;
                dgv_Locations.AllowUserToDeleteRows = true;
                dgv_Locations.AllowUserToAddRows = true;
            }
            ProjectContactType[] contacts = m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact;
            if (contacts != null && contacts.Length > 0)
            {
                foreach (ProjectContactType contact in contacts)
                {
                    int ci = dgv_Contacts.Rows.Add();
                    dgv_Contacts.Rows[ci].Cells[0].Value = contact.JobTitle == null ? "" : contact.JobTitle.Value;
                    dgv_Contacts.Rows[ci].Cells[1].Value = contact.PersonName == null ? "" : contact.PersonName.Value;
                    dgv_Contacts.Rows[ci].Cells[2].Value = contact.TelephoneTelecommunicationCommunication == null ? "" : contact.TelephoneTelecommunicationCommunication[0].CompleteNumber.Value;
                    dgv_Contacts.Rows[ci].Cells[3].Value = contact.FaxTelecommunicationCommunication == null ? "" : contact.FaxTelecommunicationCommunication.CompleteNumber.Value;
                    dgv_Contacts.Rows[ci].Cells[4].Value = contact.URIInternetCommunication == null ? "" : contact.URIInternetCommunication[0].URIID.Value;                
                }
            }
            ProjectLocationType[] locations = m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation;
            if (locations != null && locations.Length > 0)
            {
                foreach (ProjectLocationType location in locations)
                {
                    int li = dgv_Locations.Rows.Add();
                    dgv_Locations.Rows[li].Cells[0].Value = location.Name == null ? "" : location.Name.Value;
                    dgv_Locations.Rows[li].Cells[1].Value = location.PostalUnstructuredAddress == null ? "Click to enter address" :
                        location.PostalUnstructuredAddress[0].LineOne.Value + ", " + location.PostalUnstructuredAddress[0].CityName.Value;
                }
            }

        }

        #region "Contractor grid events"
        private void dgv_Contractors_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0 || e.RowIndex >= m_contractorInfo.Count)
                return;
            string cellValue = dgv_Contractors.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            switch (e.ColumnIndex)
            {
                case 0:
                    m_contractorInfo[e.RowIndex].Name = new TextType(cellValue);
                    break;
                case 1:
                    m_contractorInfo[e.RowIndex].SpecifiedProjectOrganization.BusinessTypeCode = new CodeType();
                    m_contractorInfo[e.RowIndex].SpecifiedProjectOrganization.BusinessTypeCode.Value = cellValue;
                    break;
                case 2:
                    m_contractorInfo[e.RowIndex].SpecifiedProjectOrganization.ID = new IDType(cellValue);
                    break;
                case 3:
                    break;
                default:
                    break;
            }
        }

        private void dgv_Contractors_SelectionChanged(object sender, EventArgs e)
        {
            if (dgv_Contractors.SelectedCells.Count<1)
            {
                m_currentContractor = null;
                PopulateChildGrids();
                return;
            }
            int index = -1;
            for (int i = 0; i < dgv_Contractors.SelectedCells.Count; i++ )
            {
                if (index != dgv_Contractors.SelectedCells[i].RowIndex)
                {
                    if (index == -1)
                    {
                        index = dgv_Contractors.SelectedCells[i].RowIndex;
                    }
                    else
                    {
                        index = -1;
                        break;
                    }
                }
            }
            if (index < 0 || index >= m_contractorInfo.Count)
            {
                m_currentContractor = null;
                return;
            }
            else
            {
                m_currentContractor = m_contractorInfo[index];
            }
            PopulateChildGrids();
        }

        private void dgv_Contractors_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            ContractorPartyType newContractor = new ContractorPartyType();
            newContractor.SpecifiedProjectOrganization = new ProjectOrganizationType();
            newContractor.SpecifiedProjectOrganization.PostalUnstructuredAddress = new UnstructuredAddressType[1];
            newContractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0] = new UnstructuredAddressType();
            newContractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0].LineOne = new TextType("Click to enter Address");
            dgv_Contractors.Rows[e.Row.Index - 1].Cells[3].Value = "Click to enter address";
            //e.Row.Cells[3].Value = "Click to enter address";
            m_contractorInfo.Add(newContractor);
        }

        private void dgv_Contractors_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            m_contractorInfo.RemoveAt(e.Row.Index);
        }

        private void dgv_Contractors_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0)
                return;
            if (e.ColumnIndex == 3)
            {
                ContractorPartyType currentContractor = m_contractorInfo[e.RowIndex];
                AddressForm addressForm = new AddressForm();
                addressForm.Address = currentContractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0];
                addressForm.ShowDialog(this);
                currentContractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0] = addressForm.Address;
                dgv_Contractors.Rows[e.RowIndex].Cells[3].Value = currentContractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0].LineOne.Value +
                    ", " + currentContractor.SpecifiedProjectOrganization.PostalUnstructuredAddress[0].CityName.Value;
                if (dgv_Contractors.Rows[e.RowIndex].Cells[3].Value.ToString().Trim() == "" ||
                    dgv_Contractors.Rows[e.RowIndex].Cells[3].Value.ToString().Trim() == ",")
                {
                    dgv_Contractors.Rows[e.RowIndex].Cells[3].Value = "Click to enter address";
                }
            }
        }
        #endregion

        #region "Contact grid events"
        private void dgv_Contacts_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            if (m_currentContractor == null)
                return;
            List<ProjectContactType> contactList = new List<ProjectContactType>();
            if (m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact != null &&
                m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact.Length > 0)
                contactList = m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact.ToList();
            ProjectContactType newContact = new ProjectContactType();
            contactList.Add(newContact);
            m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact = contactList.ToArray();
        }

        private void dgv_Contacts_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            if (m_currentContractor == null)
                return;
            List<ProjectContactType> contactList = m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact.ToList();
            contactList.RemoveAt(e.Row.Index);
            m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact = contactList.ToArray();
        }

        private void dgv_Contacts_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0 || m_currentContractor==null)
                return;
            ProjectContactType contact = m_currentContractor.SpecifiedProjectOrganization.DesignatedProjectContact[e.RowIndex];
            string cellValue = dgv_Contacts.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            switch (e.ColumnIndex)
            {
                case 0:
                    contact.JobTitle = new TextType(cellValue);
                    break;
                case 1:
                    contact.PersonName = new TextType(cellValue);
                    break;
                case 2:
                    contact.TelephoneTelecommunicationCommunication = new TelecommunicationCommunicationType[1];
                    contact.TelephoneTelecommunicationCommunication[0] = new TelecommunicationCommunicationType();
                    contact.TelephoneTelecommunicationCommunication[0].CompleteNumber = new TextType(cellValue);
                    break;
                case 3:
                    contact.FaxTelecommunicationCommunication = new TelecommunicationCommunicationType();
                    contact.FaxTelecommunicationCommunication.CompleteNumber = new TextType(cellValue);
                    break;
                case 4:
                    contact.URIInternetCommunication = new InternetCommunicationType[] {new InternetCommunicationType()};
                    contact.URIInternetCommunication[0].URIID = new IDType(cellValue);
                    break;
            }
        }
        #endregion

        #region "Location grid events"
        private void dgv_Locations_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            if (m_currentContractor == null)
                return;
            List<ProjectLocationType> locationList = new List<ProjectLocationType>();
            if (m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation != null &&
                m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation.Length > 0)
                locationList = m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation.ToList();
            ProjectLocationType newLocation = new ProjectLocationType();
            locationList.Add(newLocation);
            m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation = locationList.ToArray();
            dgv_Locations.Rows[e.Row.Index - 1].Cells[1].Value = "Click to enter address";
        }

        private void dgv_Locations_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            if (m_currentContractor == null)
                return;
            List<ProjectLocationType> locationList = m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation.ToList();
            locationList.RemoveAt(e.Row.Index);
            m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation = locationList.ToArray();
        }

        private void dgv_Locations_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0 || e.ColumnIndex < 0 || m_currentContractor == null)
                return;
            ProjectLocationType location = m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation[e.RowIndex];
            string cellValue = dgv_Locations.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            switch (e.ColumnIndex)
            {
                case 0:
                    location.Name = new TextType(cellValue);
                    break;
                case 1:
                    break;
                default:
                    break;
            }
        }

        private void dgv_Locations_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex < 0 || e.RowIndex < 0 || m_currentContractor==null)
                return;
            if (e.ColumnIndex == 1)
            {
                ProjectLocationType location = m_currentContractor.SpecifiedProjectOrganization.PhysicalProjectLocation[e.RowIndex];
                AddressForm addressForm = new AddressForm();
                if (location.PostalUnstructuredAddress == null || location.PostalUnstructuredAddress.Length < 1)
                {
                    location.PostalUnstructuredAddress = new UnstructuredAddressType[] { new UnstructuredAddressType() };
                }
                addressForm.Address = location.PostalUnstructuredAddress[0];
                addressForm.ShowDialog(this);
                location.PostalUnstructuredAddress[0] = addressForm.Address;
                dgv_Locations.Rows[e.RowIndex].Cells[1].Value = location.PostalUnstructuredAddress[0].LineOne.Value +
                    ", " + location.PostalUnstructuredAddress[0].CityName.Value;
                if (dgv_Locations.Rows[e.RowIndex].Cells[1].Value.ToString().Trim() == "" ||
                    dgv_Locations.Rows[e.RowIndex].Cells[1].Value.ToString().Trim() == ",")
                {
                    dgv_Locations.Rows[e.RowIndex].Cells[1].Value = "Click to enter address";
                }
            }
        }
        #endregion
    }
}
